package com.jiyun.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @projectName: 2210A-project1
 * @package: com.jiyun.gateway.filter
 * @className: MyFilter
 * @author: 耿嘉军
 * @date: 2023/8/22 10:44
 * @version: 1.0
 */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String loginPath="/loginPlay";


        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (path.contains(loginPath)){
            return chain.filter(exchange);
        }else {
            String token = request.getHeaders().getFirst("token");
            if (token==null){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.setComplete();
            }else {
                if (JWTUtil.verify(token,"1234".getBytes())){
                    return chain.filter(exchange);
                }else {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.setComplete();
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
